package com.chaosj.webmagic.scrape;

import com.alibaba.fastjson.JSONObject;
import com.chaosj.webmagic.IScrapeHandler;
import com.chaosj.webmagic.handler.IWriterHandler;
import lombok.Data;
import us.codecraft.webmagic.Spider;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @className: WriterBookHandler
 * @description:
 * @author: caoyangjie
 * @date: 2022/3/10
 **/
@Data
public class WriterBookHandler implements IScrapeHandler<String, String> {
    private JSONObject ctx;

    @Override
    public void scrape(String request) {
        List<IWriterHandler> writerHandlers = new ArrayList<>();
        ServiceLoader.load(IWriterHandler.class).forEach(handler->{
            if( handler.support(request) ){
                handler.initContext(ctx);
                writerHandlers.add(handler);
            }
        });
        Spider spider = Spider.create(writerHandlers.get(0)).addUrl(request);
        spider.run();
    }

    @Override
    public String getResult(String s) {
        return s;
    }
}
